package com.idelan.commonMessage.constant;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常统一处理
 * User gyli
 * date 2018/5/31
 */
@ControllerAdvice
public class MyHandlerAdvice {

    /**
     * 全局捕获异常，只要作用在@RequestMapping方法上，所有的信息都会被捕捉到
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public RestApi errorHandler(Exception ex){
        RestApi restApi = new RestApi();
        restApi.setErrCode(ResponseCode.RSP_FAIL);
        restApi.setMessage(ex.getMessage());
        restApi.setData("");
        return  restApi;
    }

    /**
     * 自定义异常
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public RestApi errorBussinessHandler(BusinessException ex){
        RestApi restApi = new RestApi();
        restApi.setErrCode(ex.getCode());
        restApi.setMessage(ex.getMsg());
        restApi.setData("");
        return  restApi;
    }
}
